package com.redis.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisClusterNode;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import redis.clients.jedis.JedisPoolConfig;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

/**
 * Created by junli on 2018/1/11.
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    /**
     * 连接池配置
     */
    @Bean
   // @ConditionalOnProperty(prefix = "spring.profiles.active", value = "dev", matchIfMissing = true)
    @ConditionalOnMissingBean(JedisConnectionFactory.class)
    public JedisConnectionFactory redisConnectionFactory() {
        JedisConnectionFactory connectionFactory = new JedisConnectionFactory();
        //基础连接属性
        connectionFactory.setHostName("10.211.55.6");
        connectionFactory.setPort(6379);
        connectionFactory.setDatabase(0);
        connectionFactory.setPassword("123456");
        connectionFactory.setTimeout(0);

        //连接池属性
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(10);//最大空闲连接
        poolConfig.setMaxWaitMillis(-1);//连接池最大阻塞等待时间（使用负值表示没有限制）
        poolConfig.setMinIdle(0);//连接池中的最小空闲连接

        connectionFactory.setPoolConfig(poolConfig);

        return connectionFactory;
    }

    /**
     * key 生成策略
     */
    @Bean
    public KeyGenerator keyGenerator() {
        return (Object target, Method method, Object... params) -> {
            StringBuilder key = new StringBuilder();
            key.append(target.getClass().getName());
            key.append(method.getName());
            Stream.of(params).forEach(key::append);
            return key.toString();
        };
    }

}
